package com.xinqi.modules.sys.dict.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.PageInfo;
import com.xinqi.common.base.response.Param;
import com.xinqi.common.mybatis.utils.Pages;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.modules.sys.dict.convert.DictGradeConvert;
import com.xinqi.modules.sys.dict.convert.DictSubjectConvert;
import com.xinqi.modules.sys.dict.domain.DictGradeEntity;
import com.xinqi.modules.sys.dict.domain.DictSubjectEntity;
import com.xinqi.modules.sys.dict.dto.req.AddSubjectDTO;
import com.xinqi.modules.sys.dict.dto.req.DictGradeCreateDTO;
import com.xinqi.modules.sys.dict.dto.req.DictGradeDeleteDTO;
import com.xinqi.modules.sys.dict.dto.req.DictGradeQueryDTO;
import com.xinqi.modules.sys.dict.dto.req.DictGradeUpdateDTO;
import com.xinqi.modules.sys.dict.dto.rsp.DictGradeResultDTO;
import com.xinqi.modules.sys.dict.dto.rsp.DictSubjectResultDTO;
import com.xinqi.modules.sys.dict.manager.DictGradeManager;
import com.xinqi.modules.sys.dict.manager.DictGradeSubjectManager;
import com.xinqi.modules.sys.dict.manager.DictSubjectManager;
import com.xinqi.modules.sys.dict.service.DictGradeService;
import com.xinqi.modules.sys.textbook.manager.CloudTextbookInfoManager;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 字典-年级服务层实现
 *
 * @author: linkai
 * @date: 2023/05/03
 */
@Validated
@Service("dictGradeService")
@RequiredArgsConstructor
public class DictGradeServiceImpl implements DictGradeService {
    private final DictGradeConvert dictGradeConvert;
    private final DictGradeManager dictGradeManager;

    private final DictSubjectConvert dictSubjectConvert;
    private final DictSubjectManager dictSubjectManager;

    private final DictGradeSubjectManager dictGradeSubjectManager;

    private final CloudTextbookInfoManager cloudTextbookInfoManager;

    /**
     * 分页查询 字典-年级数据
     */
    @Override
    @DS("slaver")
    public PageInfo<DictGradeResultDTO> page(Param pageable, DictGradeQueryDTO query) {
        IPage<DictGradeEntity> page = dictGradeManager.page(Pages.page(pageable), wrapper(query));
        return Pages.convert(page, dictGradeConvert::convert);
    }

    /**
     * 查询 字典-年级数据
     */
    @Override
    public List<DictGradeResultDTO> find(DictGradeQueryDTO query) {
        return dictGradeManager.list(wrapper(query)).stream()
            .map(dictGradeConvert::convert).collect(Collectors.toList());
    }

    private LambdaQueryWrapper<DictGradeEntity> wrapper(DictGradeQueryDTO query) {
        LambdaQueryWrapper<DictGradeEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(DictGradeEntity::getId, v));
        Queries.accept(query.getName(), v -> wrapper.like(DictGradeEntity::getName, v));
        wrapper.orderByAsc(DictGradeEntity::getSort);
        return wrapper;
    }

    /**
     * 根据id查询 字典-年级数据
     */
    @DS("slaver")
    @Override
    public DictGradeResultDTO findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return Optional.ofNullable(dictGradeManager.findById(id)).map(v -> {
            DictGradeResultDTO convert = dictGradeConvert.convert(v);
            convert.setSubjectList(dictGradeSubjectManager.findSubjectByGradeId(id));
            return convert;
        }).orElse(null);
    }

    /**
     * 新增 字典-年级数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(@Valid DictGradeCreateDTO dto) {
        DictGradeEntity entity = dictGradeConvert.create(dto);
        dictGradeManager.save(entity);
        dictGradeSubjectManager.addSubject(entity.getId(), dto.getSubjectIdList());
        return entity.getId();
    }

    /**
     * 根据id修改 字典-年级数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(@Valid DictGradeUpdateDTO dto) {
        Optional.ofNullable(dictGradeManager.getById(dto.getId()))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));
        DictGradeEntity entity = dictGradeConvert.update(dto);
        dictGradeSubjectManager.addSubject(entity.getId(), dto.getSubjectIdList());
        return dictGradeManager.updateById(entity);
    }

    /**
     * 根据id删除 字典-年级数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        dictGradeSubjectManager.delSubject(id);
        return dictGradeManager.removeById(id);
    }

    /**
     * 根据id删除 字典-年级数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(DictGradeDeleteDTO dto) {
        return deleteById(dto.getId());
    }

    @DS("slaver")
    @Override
    public List<DictSubjectResultDTO> findSubjectByGradeId(Long gradeId) {
        return dictGradeSubjectManager.findSubjectByGradeId(gradeId);
    }

    /**
     * 获取云课本中年纪绑定的学科
     */
    @DS("slaver")
    @Override
    public List<DictSubjectResultDTO> findBindSubjectByGradeId(Long gradeId) {
        List<Long> ids = cloudTextbookInfoManager.findByStageIdList(gradeId);
        LambdaQueryWrapper<DictSubjectEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(DictSubjectEntity::getId, ids);
        List<DictSubjectEntity> list = dictSubjectManager.list(wrapper);
        return dictSubjectConvert.convert(list);
    }

    @DS("slaver")
    @Override
    public List<DictSubjectResultDTO> findSubjectByStageId(Long stageId) {
        return dictGradeSubjectManager.findSubjectByStageId(stageId);
    }

    @DS("slaver")
    @Override
    public List<DictSubjectResultDTO> findSubjectByVersionId(Long versionId) {
        return dictGradeSubjectManager.findSubjectByVersionId(versionId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addSubject(AddSubjectDTO dto) {
        return dictGradeSubjectManager.addSubject(dto.getGradeId(), dto.getSubjectIdList());
    }

    @Override
    public Boolean isExistName(String name, Long oId) {
        CommonErrors.BAD_REQUEST.check(StringUtils.isNotEmpty(name), "名称不能为空");
        return dictGradeManager.isExistName(name, oId);
    }

}
